package com.yjz.jvm.juc.Semaphore;

import java.util.concurrent.Semaphore;

public class SemaphoreExample {
    private Semaphore semaphore = new Semaphore(0);

    public void waitForCondition() throws InterruptedException {
        // 等待条件满足
        semaphore.acquire();
        System.out.println("Condition is satisfied. Proceeding...");
    }

    public void notifyCondition() {
        // 满足条件，释放许可,  There is no requirement that a thread that releases a permit must  have acquired that permit by calling  acquire
        // 没调用acquire方法也可以释放
        semaphore.release();
    }

    public static void main(String[] args) {
        SemaphoreExample example = new SemaphoreExample();

        // 创建一个线程等待条件
        Thread waitingThread = new Thread(() -> {
            try {
                example.waitForCondition();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        // 创建另一个线程通知条件满足
        Thread notifyingThread = new Thread(() -> {
            // 模拟条件满足
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            example.notifyCondition();
        });

        waitingThread.start();
        notifyingThread.start();
    }
}